package com.batdream.message.netty;

import com.batdream.message.service.ChatService;
import com.batdream.message.utils.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.Level;
import org.springframework.stereotype.Component;

/**
 * @author Wang Chen Peng
 * @date 2019/01/04
 * describe: 用来处理心跳的自定义handler
 * 继承 ChannelInboundHandlerAdapter 从而不需要实现 SimpleChannelInboundHandler<TextWebSocketFrame> 中的channelRead0方法
 */
@Log4j2
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private static UserChannelContext userChannelContext;
    private ChannelUserContext channelUserContext;

    public void init(){
        userChannelContext = (UserChannelContext) SpringUtil.getApplicationContext().getBean("userChannelContext");
        channelUserContext = (ChannelUserContext) SpringUtil.getApplicationContext().getBean("channelUserContext");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //判断是不是空闲状态事件 用于出发用户事件 包含读,写,读空闲,写空闲,读写空闲
        if (evt instanceof IdleStateEvent){
            //转换类型
            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;

            //读空闲
            if (idleStateEvent.state()== IdleState.READER_IDLE){
                log.debug("id : {} 进入读空闲", ctx.channel().id().asLongText());
            }
            //写空闲
            else if (idleStateEvent.state()== IdleState.WRITER_IDLE){
                log.debug("id : {} 进入写空闲", ctx.channel().id().asLongText());
            }
            //读写空闲
            else if (idleStateEvent.state()== IdleState.ALL_IDLE){
                Channel channel = ctx.channel();
                String longId = channel.id().asLongText();
                log.debug("id : {} 进入读写All空闲", longId);
                //关闭无用的channel
                channel.close();
                /*//从容器中移除
                String userId = channelUserContext.getUserId(longId);
                channelUserContext.remove(longId);
                userChannelContext.remove(userId);
                此处不从容器中移除 在回调handlerRemoved 中进行移除
                */


            }

        }
    }
}
